<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            :center="true"
            width="350px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" :rules="formRules">
                <el-form-item prop="goodsType">
                    <el-radio-group v-model="formData.goodsType">
                        <el-radio size="large" border :value="1">现金商品</el-radio>
                        <el-radio size="large" border :value="2">积分商品</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import { selection } from '@/servers/goods/api/supplyChainshangpinguanli'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()

const popupTitle = ref('选择加入')
const formData = reactive<{
    goodsIds: any[]
    goodsType: number | null
}>({
    goodsIds: [],
    goodsType: null
})

const formRules = reactive({
    goodsType: [
        {
            required: true,
            message: '请选择商品类型',
            trigger: ['blur']
        }
    ]
})

const handleSubmit = async () => {
    if (formData.goodsIds.length === 0) {
        ElMessage.warning('请先选择商品')
        return
    }
    if (!formData.goodsType) {
        ElMessage.warning('请先选择加入的商品类型')
        return
    }
    await selection(
        {},
        {
            goodsIds: formData.goodsIds as any,
            goodsType: formData.goodsType
        }
    )

    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (goodsIds: any[]) => {
    formData.goodsIds = goodsIds
    popupRef.value?.open()
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open
})
</script>
